angular.module('U9ImHd.services')

.factory('ConnectService', ['$q', '$http', 'Config', 'APPCONSTANTS',
    function($q, $http, Config, APPCONSTANTS) {
        var connectDefer = $q.defer(),
            o = {
                loaded: connectDefer.promise
            };

        var _connect = {},
            _portal = {};

        o.set = function (address, port) {
            var defer = $q.defer();

            _connect.address = address;
            _connect.port = port;
            Config.set(_connect).finally(function () {
                defer.resolve();
            });

            return defer.promise;
        };
        o.get = function (key) {
            return key ? _connect[key] : angular.copy(_connect);
        };
        o.getPortal = function (key) {
            return key ? _portal[key] : angular.copy(_portal);
        };
        o.test = function (address, port) {
            var defer = $q.defer();

            $http({
                method: 'POST',
                url: 'http://' + address + ':' + port + APPCONSTANTS.connectTestURL,
                timeout: APPCONSTANTS.httpTimeOut
            }).then(function () {
                defer.resolve();
            }, function () {
                defer.reject();
            });

            return defer.promise;
        };

        init();

        return o;

        function init () {
            Config.loaded.finally(function () {
                // _connect.address = Config.get('address', APPCONSTANTS.defaultAddress);
                // _connect.port = Config.get('port', APPCONSTANTS.defaultPort);
                // connectDefer.resolve();
                var address = Config.get('address', APPCONSTANTS.defaultAddress),
                    port = Config.get('port', APPCONSTANTS.defaultPort);
                if (address && port) {
                    _connect.address = address;
                    _connect.port = port;
                }
                _portal.address = APPCONSTANTS.defaultPortalAddress;
                _portal.port = APPCONSTANTS.defaultPortalPort;
                connectDefer.resolve();
            });
        }
    }
]);
